package com.gitee.fsadmin.interceptor;

import com.gitee.fsadmin.common.context.UserContext;
import com.gitee.fsadmin.common.enums.StatusEnum;
import com.gitee.fsadmin.common.exception.LoginFailureException;
import com.gitee.fsadmin.common.user.User;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.route.PathRule;
import org.noear.solon.core.route.RouterInterceptor;
import org.noear.solon.core.route.RouterInterceptorChain;


/**
 * @author tanghc
 */
@Slf4j
@Component
public class LoginInterceptor implements RouterInterceptor {

    @Override
    public PathRule pathPatterns() {
        String[] excludes = {
                "/", "/error", "/sys/login",
                // 排除前端资源
                "/*.html", "/*.ico", "/*.png", "/*.json", "/static/**", "/assets/**"
        };
        return new PathRule().include("/**").exclude(excludes);
    }

    @Override
    public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain) throws Throwable {
        User user = UserContext.getUser();
        if (user == null || StatusEnum.of(user.getStatus()) == StatusEnum.DISABLED) {
            log.error("登录失败, 客户端ip:{}, uri:{}", ctx.realIp(), ctx.uri());
            throw new LoginFailureException("登录失败");
        }
        chain.doIntercept(ctx, mainHandler);
    }
}
